package org.example.myleet.p995;

public class Solution1 {
    /**
     * 1886 ms
     * 直接模拟法，复杂度O(NK)
     */
    public int minKBitFlips(int[] A, int K) {
        int flipIdx = 0, n = A.length, endIdx = n-K, count = 0;
        while (flipIdx <= endIdx) {
            for (int i=flipIdx; i<n; i++) {
                if (A[i] == 0) {
                    break;
                }
                ++flipIdx;
            }
            if (flipIdx+K > n) {
                break;
            }
            flip(A, flipIdx, flipIdx+K);
            ++flipIdx;
            ++count;
        }
        for (int i=flipIdx; i<n; i++) {
            if (A[i] == 0) {
                return -1;
            }
        }
        return count;
    }

    private void flip(int[] A, int start, int end) {
        for (int i=start; i<end; i++) {
            A[i] = A[i]^1;
        }
    }
}
